package com.example.forum.controller;


import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.ArticleReply;
import com.example.forum.model.User;
import com.example.forum.services.impl.ArticleReplyServiceImpl;
import com.example.forum.services.impl.ArticleServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Api(tags = "回复接口")
@Slf4j
@RestController
@RequestMapping("/reply")
public class ArticleReplyController {
    @Resource
    private ArticleServiceImpl articleService;

    @Resource
    private ArticleReplyServiceImpl articleReplyService;


    @ApiOperation("回复帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("帖子Id")@RequestParam("articleId")@NonNull Long articleId,
                            @ApiParam("帖子内容")@RequestParam("content")@NonNull String content) {
        //获取当前用户
        HttpSession session = request.getSession(false);
        User  user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //校验用户是否禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //获取文章对象
        Article article = articleService.selectById(articleId);
        //是否存在或已删除
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断是否封贴
        if (article.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }

        //构造要回复的对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setPostUserId(user.getId());
        articleReply.setContent(content);

        //调用service
        articleReplyService.create(articleReply);

        return AppResult.success();
    }
    @ApiOperation("回复帖子列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(Long articleId) {
       //判断帖子是否存在
        Article article = articleService.selectById(articleId);
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //调用service
        List<ArticleReply> articleReplies = articleReplyService.selectByArticleId(articleId);

         return AppResult.success(articleReplies);

    }
}
